package com.dlc.felear.xiaoensale.helper;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.util.Log;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.utils.HandlerTemperatorUtil;
import com.dlc.felear.xiaoensale.utils.HexUtil;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Usbhelper {
    private static final String TAG="Usbhelper";
    private static final String ACTION_USB_PERMISSION="action_usb_permission";
    private static final String USB_STATE="android.hardware.usb.action.USB_STATE";
    private static Usbhelper usbhelper;
    private Context context;
    private int productId1=65535;
    private int productId2=21778;
    private UsbManager manager;
    private PendingIntent mPermissionIntent;
    private UsbSerialDevice serial;
    private ScheduledExecutorService scheduledThreadPool;
    private byte[] tempData1=new byte[]{(byte) 0xAD,(byte) 0x02,(byte) 0x0D,(byte) 0xD0,(byte) 0x4E,(byte) 0x00};
    private byte[] tempData2=new byte[]{(byte) 0xA1,(byte) 0x00,(byte) 0x64,(byte) 0x07,(byte) 0x01};
    private long lastRecieve=0;

    public static Usbhelper getUsbhelper(Context context) {
        if(usbhelper==null){
          synchronized (Usbhelper.class){
              if(usbhelper==null){
                  usbhelper=new Usbhelper(context);
              }
          }
        }
        return usbhelper;
    }

    private Usbhelper(Context context) {
        this.context = context;
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(USB_STATE);
        context.registerReceiver(mUsbPermissionActionReceiver,filter);
        mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        scheduledThreadPool = new ScheduledThreadPoolExecutor(3);
        // 获取系统服务得到UsbManager实例
        manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        lastRecieve=System.currentTimeMillis();
        loop();
    }

    private void getUsbDevices(){
        //查找所有插入的设备
        for(String d: manager.getDeviceList().keySet()){
            Log.e(TAG,"d="+d+"---"+JsonHelper.toJson(manager.getDeviceList().get(d)));
            UsbDevice usbDevice=manager.getDeviceList().get(d);
            if(usbDevice.getProductId()==productId1||usbDevice.getProductId()==productId2){
                connectUsb(usbDevice);
            }
        }

    }

    private void loop(){
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                sendData(tempData1);
                initUsb();
            }
        }, 3, 2, TimeUnit.SECONDS);
    }

    private void sendData(byte[] data){
        Log.e(TAG,"data="+HexUtil.bytes2HexString(data));
        if(serial!=null){
            serial.write(data);
        }
    }

    private void initUsb(){
        if(System.currentTimeMillis()-lastRecieve>5000){
            getUsbDevices();
        }
    }

    private void connectUsb(UsbDevice usbDevice){
        if(!manager.hasPermission(usbDevice)){
            Log.e(TAG,"需要申请权限:"+JsonHelper.toJson(usbDevice));
            manager.requestPermission(usbDevice, mPermissionIntent);
           return;
        }
        afterGetUsbPermission(usbDevice);
    }

    private void afterGetUsbPermission(UsbDevice usbDevice){
        Log.e(TAG,"已获取权限"+manager.hasPermission(usbDevice));
        UsbDeviceConnection  connection=manager.openDevice(usbDevice);
        serial=UsbSerialDevice.createUsbSerialDevice(usbDevice,connection);
        readData();
    }

    private void readData(){
//        Log.e(TAG,"usbSerialDevice="+serial);
        if(serial==null){
            return;
        }
        serial.open();
        serial.setBaudRate(9600);
        serial.setDataBits(UsbSerialInterface.DATA_BITS_8);
        serial.setParity(UsbSerialInterface.PARITY_ODD);
        serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
        serial.read(new UsbSerialInterface.UsbReadCallback() {
            @Override
            public void onReceivedData(byte[] bytes) {
                lastRecieve=System.currentTimeMillis();
                handlerRecieveData(bytes);
//                Log.e(TAG,"data="+ HexUtil.bytes2HexString(bytes));
            }
        });
        sendData(tempData2);
    }

    private void handlerRecieveData(final byte[] bytes){
        Log.e(TAG,"bytes="+HexUtil.bytes2HexString(bytes)+" size="+bytes.length);
        scheduledThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                if(bytes[0]==0xBB){
                    sendData(tempData2);
                    return;
                }
                HandlerTemperatorUtil.getInstance().recievetempertor(bytes);
            }
        });
    }


    private final BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG,"action="+action);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if(null != usbDevice){
                            afterGetUsbPermission(usbDevice);
                        }
                    }
                    else {
                        Toast.makeText(context, String.valueOf("Permission denied for device" + usbDevice), Toast.LENGTH_LONG).show();
                    }
                }
            }else if(USB_STATE.equals(action)){
                getUsbDevices();
            }
        }
    };

}
